package cn.yunhe.control;

import cn.yunhe.entity.FriendMessage;
import cn.yunhe.entity.User;
import cn.yunhe.server.FriendServer;
import cn.yunhe.server.UserServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/EnsureAddFriendServlet")
public class EnsureAddFriendServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取好友id和昵称
        int fuId = Integer.parseInt(request.getParameter("fuId"));
        String fuName = request.getParameter("fuName");
        //获取用户账号密码
        String username = (String) session.getAttribute("username");
        String password = (String) session.getAttribute("password");
        User user = new User(username, password);
        //新建server对象
        UserServer userServer = new UserServer();
        FriendServer friendServer = new FriendServer();
        //通过用对象获取用户全部信息
        User user1 = userServer.login(user);
        //向数据库添加好友关系,同时插入两次,确保添加好友的同时对方的好友列表也包含用户
        FriendMessage friendMessage1 = new FriendMessage(user1.getuId(), user1.getuName(), fuId, fuName); //新建好友消息对象
        FriendMessage friendMessage2 = new FriendMessage(fuId, fuName, user1.getuId(), user1.getuName()); //新建好友消息对象
        boolean flag1 = friendServer.EnsureAddFriend(friendMessage1);
        boolean flag2 = friendServer.EnsureAddFriend(friendMessage2);
        if (flag1 && flag2) {
            request.setAttribute("result", "好友添加成功!!");
            request.getRequestDispatcher("friendMessage.jsp").forward(request, response);
        } else {
            request.setAttribute("result", "好友添加失败!!");
            request.getRequestDispatcher("friendMessage.jsp").forward(request, response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
